/*
 * @lc app=leetcode id=113 lang=cpp
 *
 * [113] Path Sum II
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        vector<vector<int>> ret;   
        if (!root) {
            return ret;
        }
        vector<int> path;
        loop(root, sum, path, ret);
        return ret;
    }

    void loop(TreeNode* root, int sum, vector<int>& path, vector<vector<int>>& ret) {

        if (!root) {
            return ;
        }

        sum = sum - root->val;
        path.push_back(root->val);
        if (!root->left && !root->right) {
            if (sum == 0) {
                ret.push_back(path);
            } 
            path.pop_back();
            return ;
        }
        
        loop(root->left, sum, path, ret) ;
        loop(root->right, sum, path, ret);
        path.pop_back();
    }
};

